package com.ad.pet.app.account.info;

import android.Manifest;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.account.AccountContract;
import com.ad.pet.app.account.AccountPresenter;
import com.ad.pet.app.photo.model.ImageItem;
import com.ad.pet.common.data.utils.FileUtil;
import com.ad.pet.common.data.utils.glide.GlideUtil;
import com.ad.pet.common.data.utils.ui.BottomSheetUtil;
import com.ad.pet.common.data.utils.ui.DialogUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.PermissionManager;
import com.ad.pet.common.structure.PhotoManager;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.presenter.photo.PhotoContract;
import com.ad.pet.common.structure.presenter.photo.PhotoPresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.models.remote.account.Account;
import com.ad.pet.models.remote.account.AccountPet;
import com.ad.pet.models.remote.account.pet.PetCateFirst;
import com.ad.pet.models.remote.account.pet.PetColor;
import com.ad.pet.ui.pickerview.OptionsPickerView;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * Created by liuyixiang on 2019/10/21.
 */

public class PetInfoActivity extends AppToolbarActivity implements AccountContract.View, PhotoContract.View {
    private boolean mIsDel;
    String id;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.et_pet_name)
    EditText etPetName;
    @BindView(R.id.tv_pet_sex)
    TextView tvPetSex;
    @BindView(R.id.relative_sex)
    RelativeLayout relativeSex;
    @BindView(R.id.tv_pet_birth)
    TextView tvPetBirth;
    @BindView(R.id.relative_birth)
    RelativeLayout relativeBirth;
    @BindView(R.id.tv_pet_type)
    TextView tvPetType;
    @BindView(R.id.relative_type)
    RelativeLayout relativeType;
    @BindView(R.id.tv_weight)
    TextView tvWeight;
    @BindView(R.id.relative_weight)
    RelativeLayout relativeWeight;
    @BindView(R.id.tv_sterilization)
    TextView tvSterilization;
    @BindView(R.id.relative_sterilization)
    RelativeLayout relativeSterilization;
    @BindView(R.id.tv_color)
    TextView tvColor;
    @BindView(R.id.relative_color)
    RelativeLayout relativeColor;
    @BindView(R.id.tv_delete)
    TextView tvDelete;

    @Inject
    AccountPresenter accountPresenter;
    @BindView(R.id.et_weight)
    EditText etWeight;
    private Drawable drawableMale;
    private Drawable drawableFamale;
    private List<PetCateFirst> petCateFirst;
    private List<PetColor> petColors;
    String cateId;
    String colorId;
    String userHeadImg;//b-ssl.duitang.com/uploads/item/201812/06/20181206192134_hYnkG.jpeg";

    private File mFile;
    @Inject
    PermissionManager mPermissionManager;

    private BottomSheetDialog mPhotoDialog;
    private View mDialogView;
    private Button mButCancel;
    private Button mButOpen;
    private Button mButPhoto;

    @Inject
    FileUtil mFileUtil;
    @Inject
    PhotoPresenter mPhotoPresenter;
    @Inject
    RxDisposable mRxDisposable;
    private AccountPet accountPet;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mStatusLayoutManager.showContent();
        mToolbar.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        mToolbar.setLeftIcon(R.drawable.whitefanhui);
        mToolbar.setNextText("保存");
        mToolbar.setNextOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(userHeadImg)){
                    ToastUtil.getToastUtil().showShort("请选择宠物头像");
                    return;
                }
                if (TextUtils.isEmpty(etPetName.getText().toString())){
                    ToastUtil.getToastUtil().showShort("请输入名称");
                    return;
                }
                if (TextUtils.isEmpty(accountPet.getBirthday())){
                    ToastUtil.getToastUtil().showShort("请选择生日");
                    return;
                }
                if (TextUtils.isEmpty(accountPet.getCategory_id())){
                    ToastUtil.getToastUtil().showShort("请选择品种");
                    return;
                }
                if (TextUtils.isEmpty(etWeight.getText().toString())){
                    ToastUtil.getToastUtil().showShort("请输入体重");
                    return;
                }
                if (TextUtils.isEmpty(accountPet.getColor_id())){
                    ToastUtil.getToastUtil().showShort("请选择毛色");
                    return;
                }

                accountPresenter.upPetInfo(userHeadImg,etPetName.getText().toString(),accountPet.getSex()+"",accountPet.getBirthday(),accountPet.getCategory_id(),etWeight.getText().toString(),accountPet.getIs_sterilisate()+"",accountPet.getColor_id(),"-1".equals(id)?"":id);

            }
        });
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_petinfo;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void initViews() {
        accountPresenter.onCreate(this);
        mPhotoPresenter.onCreate(this);
        id = getIntent().getStringExtra("id");
        tvDelete.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tvDelete.getPaint().setAntiAlias(true);//抗锯齿

        drawableMale = getResources().getDrawable(
                R.drawable.ic_male);
        drawableFamale = getResources().getDrawable(
                R.drawable.ic_fale);

        if (!"-1".equals(id)) {
            accountPresenter.getPetInfo(id);

        } else {
            tvDelete.setVisibility(View.GONE);
            accountPet = new AccountPet();
            setSex(0);
            tvSterilization.setText("未绝育");
        }
        accountPresenter.getPetCategory();
        accountPresenter.getPetColor();

        mPermissionManager.setRxPermissions(new RxPermissions(this));
        mDialogView = LayoutInflater.from(this).inflate(R.layout.layout_dialog_photo, null);
        mButCancel = mDialogView.findViewById(R.id.but_cancel);
        mButOpen = mDialogView.findViewById(R.id.but_open);
        mButPhoto = mDialogView.findViewById(R.id.but_photo);
        mButOpen = mDialogView.findViewById(R.id.but_open);

        mPhotoDialog = new BottomSheetDialog(this);
        mPhotoDialog.setContentView(mDialogView);
        BottomSheetUtil.statusBarTranslucent(mPhotoDialog);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvents() {
        mButPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
                mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        Navigation.goPhotoLoaderActivity(mActivity, PhotoManager.REQUEST_CODE_CHECK_IMAGE, 0);
                    }
                }, getString(R.string.storage), Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE));
            }
        });
        mButCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
            }
        });
        //打开相机
        mButOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
                //打开相机
                mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        mFile = new File(mFileUtil.getRootDir(), System.currentTimeMillis() + ".jpg");
                        //打开相机
                        PhotoManager.openCamera(mActivity, mFile, PhotoManager.REQUEST_CODE_OPEN_CAMERA);
                    }
                }, getString(R.string.camera), Manifest.permission.CAMERA));
            }
        });

        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.createDialog(mActivity, getString(R.string.is_confirm_delete), getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        accountPresenter.deletePet(id);
                    }
                }).show();
            }
        });
        relativeType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (petCateFirst == null)
                    return;
                OptionsPickerView pvOptions = new OptionsPickerView.Builder(mActivity, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {
                        tvPetType.setText(petCateFirst.get(options1).getCategory_name());
                        cateId = petCateFirst.get(options1).getCategory_id();
                        accountPet.setCategory_id(cateId);
                    }
                }).build();

//                List<List<PetCateSecond>> list1 = new ArrayList<>();
//                for (int i = 0; i < petCateFirst.size(); i++) {
//                    list1.add(petCateFirst.get(i).getChild_list());
//                }
//                List<List<List<PetCate>>> list2 = new ArrayList<>();
//                for (int i = 0; i < list1.size(); i++) {
//                    List<List<PetCate>> tempList = new ArrayList<>();
//                    for (int j = 0; j < list1.get(i).size(); j++) {
//                        tempList.add(list1.get(i).get(j).getChild_list());
//                    }
//                    list2.add(tempList);
//                }
                pvOptions.setPicker(petCateFirst);//添加数据源
                pvOptions.show();
            }
        });

        relativeColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (petColors == null)
                    return;
                OptionsPickerView pvOptions = new OptionsPickerView.Builder(mActivity, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3, View v) {

                        colorId = petColors.get(options1).getColor_id();
                        tvColor.setText(petColors.get(options1).getColor_name());
                        accountPet.setColor_id(colorId);
                    }
                }).build();
                pvOptions.setPicker(petColors);
                pvOptions.show();
            }
        });
        relativeBirth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DatePickerDialog(mActivity, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        String time = i + "/" + (i1 + 1) + "/" + i2;
                        tvPetBirth.setText(time);
//                        accountPet.setBirthday(TimeFormatUtil.dateToStamp(time));
                        accountPet.setBirthday(time);
                    }
                }, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
            }
        });

        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BottomSheetUtil.collapsedDialog(mDialogView);
                mPhotoDialog.show();
            }
        });

        relativeSex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i = 0;
                if (accountPet == null) {

                    i = 0;
                } else {
                    i = accountPet.getSex();
                }

                DialogUtil.createSingleChoiceItemsDialog(mActivity, "选择性别", new String[]{"保密", "弟弟", "妹妹"}, i, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        setSex(i);
                        accountPet.setSex(i);
                    }
                }).show();
            }
        });

        relativeSterilization.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                  int  i = accountPet.getIs_sterilisate();


                DialogUtil.createSingleChoiceItemsDialog(mActivity, "是否绝育？", new String[]{"未绝育", "已绝育"}, i, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        tvSterilization.setText(i==0?"未绝育":"已绝育");
                        accountPet.setIs_sterilisate(i);
                    }
                }).show();
            }
        });


    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent())

                .activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }

    @Override
    public void error(int code, String msg) {
            ToastUtil.getToastUtil().showShort(msg);
    }

    @Override
    public void loginOutSuccess() {

    }

    @Override
    public void getUserInfoSuccess(Account account) {

    }

    @Override
    public void getPetInfoSuccess(AccountPet accountPublic) {
        accountPet = accountPublic;
//        tvPetBirth.setText(TimeFormatUtil.stampToDate(Long.valueOf(accountPublic.getBirthday())));
        tvPetBirth.setText(accountPublic.getBirthday());
        etPetName.setText(accountPublic.getPet_name());
        setSex(accountPublic.getSex());
        tvColor.setText(accountPublic.getColor_name());
        tvPetType.setText(accountPublic.getCategory_name());
        etWeight.setText(accountPublic.getWeight());
        tvSterilization.setText(accountPublic.getIs_sterilisate()==0?"未绝育":"已绝育");
        GlideUtil.load(mActivity,accountPublic.getPet_headimg(),ivHead);
        userHeadImg = accountPublic.getPet_headimg();
    }

    @Override
    public void uploadHead(String user) {
        GlideUtil.load(mActivity, user, ivHead);
        this.userHeadImg = user;
    }

    @Override
    public void upPetInfoSuccesss() {
        RxBus.getDefault().post("up_pet_head_success");
        ToastUtil.getToastUtil().showShort(getString(R.string.add_address_success));
        mIsDel = true;
        finish();
    }

    @Override
    public void getPetCategorySuccess(List<PetCateFirst> petCateFirst) {
        this.petCateFirst = petCateFirst;

    }

    @Override
    public void getPetColorSuccess(List<PetColor> petColor) {
        petColors = petColor;
    }

    @Override
    public void deletePetSuccess() {
        ToastUtil.getToastUtil().showShort("删除成功");
        mIsDel = true;
        finish();
    }

    @Override
    public void upPersonInfoSuccess() {

    }


    private void setSex(int type) {
        if (type == 0) {
            tvPetSex.setText("保密");
        } else {
            tvPetSex.setCompoundDrawablesWithIntrinsicBounds(type == 1 ? drawableMale : drawableFamale,
                    null, null, null);
            tvPetSex.setText(1==type?"弟弟":"妹妹");
        }
    }

    @Override
    public void finish() {
        if (!mIsDel) {
            DialogUtil.createDialog(mActivity, getString(R.string.is_cancel_add_shou_huo_dizhi), getString(R.string.confirm), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mIsDel = true;
                    PetInfoActivity.this.finish();
                }
            }).show();
        } else {
            super.finish();
        }

    }

    @Override
    public void compressComplete(File file) {
        accountPresenter.uploadHead(file, "pet_avator");
    }

    @Override
    public void photoCallback(String path) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PhotoManager.REQUEST_CODE_CHECK_IMAGE:
                    //选择图片回调 并裁剪
                    ArrayList<ImageItem> path = data.getParcelableArrayListExtra("path");
                    mFile = new File(mFileUtil.getHeaderDir().getPath(), System.currentTimeMillis() + ".jpg");
                    PhotoManager.crop(this, mFile, new File(path.get(0).getImagePath()), PhotoManager.REQUEST_CODE_CROP_CODE);
                    break;
                case PhotoManager.REQUEST_CODE_OPEN_CAMERA:
                    //相机回调
                    PhotoManager.crop(this, mFile, mFile, PhotoManager.REQUEST_CODE_CROP_CODE);
                    break;
                case PhotoManager.REQUEST_CODE_CROP_CODE:
                    //裁剪回调
                    //压缩
                    mPhotoPresenter.compressPhoto(mFile);
                    break;

            }
        }
    }
}
